#!/usr/bin/env python3
# filename: forms.py

from flask_wtf import FlaskForm, RecaptchaField
from flask import session, flash
from flask_login import current_user
from wtforms import (
        StringField,
        TextField,
        TextAreaField,
        BooleanField,
        ValidationError,
        PasswordField
        )

from wtforms.validators import DataRequired, Length, EqualTo, URL, Email
from hzsaiblog.models import User


class CommentForm(FlaskForm):
    """Form validator for comments."""

    # Set some field for input data

    name = StringField(
            'Name',
            validators=[DataRequired(), Length(max=255)])
    email = StringField(
        'Email',
        validators=[DataRequired(), Email()]
    )
    text = TextAreaField(u'Comment', validators=[DataRequired()])


class LoginForm(FlaskForm):
    """Form for login."""

    username = StringField(
            'Username',
            validators=[DataRequired(), Length(max=255)])
    password = PasswordField('Password', [DataRequired()])
    remember = BooleanField("Remember Me")

    #
    def validate(self):
        """Validator for check the account information."""

        check_validate = super(LoginForm, self).validate()

        # check the form
        if not check_validate:
            return False

        # check the username's existence
        user = User.query.filter_by(username=self.username.data).first()
        if not user:
            self.username.errors.append('Invalid username or password.')
            return False

        if not user.check_password(self.password.data):
            self.password.errors.append('Invalid username or password.')
            return False

        return True


class RegisterForm(FlaskForm):
    """Register Form."""

    username = StringField('Username', [DataRequired(), Length(max=255)])
    password = PasswordField('Password', [DataRequired(), Length(min=6)])
    confirm = PasswordField(
            'Confirm Password',
            [DataRequired(),
                EqualTo('password', message='Passwords must match')])
    # recaptcha = RecaptchaField()
    recaptcha = StringField(
            'Captcha',
            [DataRequired(),
                Length(
                    min=5,
                    max=5,
                    message="Please enter right Captcha code."
                    )]
                )

    def validate(self):
        check_validate = super(RegisterForm, self).validate()

        # if validator no pass
        if not check_validate:
            flash("validate check failed.")
            return False

        # check the user whether already exist.
        user = User.query.filter_by(username=self.username.data).first()
        if user:
            flash("Username already exists.")
            self.username.errors.append('User with that name alreay exist.')
            return False

        if session['captcha_key'] != self.recaptcha.data:
            return False

        # successful check
        return True


class PostForm(FlaskForm):
    """Post Form."""

    title = StringField('Title', validators=[DataRequired(), Length(max=255)])
    latest_tag = StringField('Tag', validators=[DataRequired(), Length(max=255)])
    text = TextAreaField('Blog Content', validators=[DataRequired()])
